package com.sikadwafastdaisfondturbo.pretloan.ui.process.page

import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.ProcessContactInfoAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageProcessCommonBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.ProcessActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.StringDeepCopy
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.json.JSONArray
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 11:29
 * @Annotation：流程 - 联系人信息
 */
class ContactPage(): ProFragment() {
    lateinit var binding: PageProcessCommonBinding
    private var stepAct: ProcessActivity? = null
    private var stepItem: JSONObject? = null
    //内容列表
    private var mContactAdapter: ProcessContactInfoAdapter? = null

    constructor(act: ProcessActivity,data: JSONObject): this(){
        this.stepAct = act
        this.stepItem = data
    }
    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageProcessCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        initRvList()
    }

    override fun initListener() {
        //下一步
        binding.btnNext.setOnClickListener {
            if (!isAllowSubmit()){
                showToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path",stepItem!!.optString("apiUrl").replace("/",""))
            }
            //拼接上传数据格式
            val paramArray = JSONArray()
            for (i in 0..<mContactAdapter!!.itemCount){
                val obj = JSONObject()
                val dataArray = mContactAdapter!!.getItem(i).optJSONArray("dataList")
                for (j in 0..<dataArray!!.length()){
                    val item = dataArray.optJSONObject(j)
                    obj.put(item.optString("paramName"),item.optJSONObject("selectItem").optString("value"))
                }
                paramArray.put(obj)
            }
            params.put(stepItem!!.optString("contactParamName"),paramArray)
            val act = context as ProcessActivity
            act.submitAction(params)

            addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_NEXT,stepItem!!.optString("stepTitle")),"")
        }
    }

    override fun initData() {
        // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
        val stringCopy = StringDeepCopy(stepItem!!.optString("dataList"))
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<stepItem!!.optInt("itemCount")){
            val obj = JSONObject()
            obj.put("brandTitle",getString(R.string.process_contact)+(i+1).toString())
            val dataArray = JSONArray(stringCopy.content)
            for (j in 0..<dataArray.length()){
                val dataObj = dataArray.optJSONObject(j)
                dataObj.put("title",dataObj.optString("title"))
                when(dataObj.optString("action")){
                    "CONTACT_GROUP_RELATION",
                    "SELECT" -> {
                        dataObj.put("action","SELECT")
                        val valueArray = stepItem!!.optJSONArray("relationShips").optJSONArray(i)
                        val values = JSONArray()
                        for (n in 0..<valueArray.length()){
                            val value = JSONObject()
                            value.put("title",valueArray.optString(n))
                            value.put("value",valueArray.optString(n))
                            values.put(value)
                        }
                        dataObj.put("values",values)
                    }
                    "CONTACT_GROUP_PHONE" -> {//联系电话
                        dataObj.put("action","CONTACT_GROUP_PHONE")
                    }
                    else -> {
                        dataObj.put("action","INPUT")
                    }
                }
            }
            obj.put("dataList",dataArray)
            dataList.add(obj)
        }
        mContactAdapter!!.data = dataList
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRvList() {
        binding.rvCommon.setHasFixedSize(true)
        binding.rvCommon.isNestedScrollingEnabled = false
        binding.rvCommon.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.rvCommon.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        binding.rvCommon.addItemDecoration(LinearDecoration(0,0,0,topDecoration))
        mContactAdapter = ProcessContactInfoAdapter(binding.root,binding.rvCommon)
        binding.rvCommon.adapter = mContactAdapter!!
        binding.rvCommon.itemAnimator = DefaultItemAnimator()
        mContactAdapter!!.setOnChildItemSelectMobileListener(object : ProcessContactInfoAdapter.IChildItemSelectMobileListener {
            override fun onChildSelectMobileClick(parentPosition: Int, childModel: JSONObject) {
                if (stepAct == null){
                    return
                }
                stepAct!!.pickContact?.startPickContact { contactName, contactMobile ->
                    HHLog.e(">>>>>>>>>>>>>>>>>>>>>$contactName>>>>>>>$contactMobile")

                    val obj = JSONObject()
                    obj.put("title",contactMobile)
                    obj.put("value",contactMobile)
                    childModel.put("selectItem", obj)
                    mContactAdapter!!.notifyItemChanged(parentPosition)

                    addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT, childModel.optString("paramName")), "$contactName:$contactMobile")
                }
            }
        })
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<mContactAdapter!!.itemCount){
            val dataArray = mContactAdapter!!.getItem(i).optJSONArray("dataList")
            for (j in 0..<dataArray!!.length()){
                val item = dataArray.optJSONObject(j)
                dataList.add(item)
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_STEP_CONTACT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_STEP_CONTACT_END,"")
    }
}